package models;

import java.util.ArrayList;
import viewers.Observer;

/**
 * Model base for a Model-View-Controller Event-Driven program
 * @author benjamin
  	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class Model {
	private ArrayList<Observer> observers; //observer pattern
	/**
	 * Default constructor
	 */
	public Model(){
		observers = new ArrayList<Observer>();
	}
	/**
	 * Registers a new observer
	 * @param obj
	 */
	public synchronized void registerObserver(Observer obj){
		if (!observers.contains(obj))
			observers.add(obj);
	}
	/**
	 * Deregister an existing observer
	 * @param obj
	 */
	public synchronized void deregisterObserver(Observer obj){
		if (observers.contains(obj))
			observers.remove(obj);
		else
			throw new IllegalArgumentException("Observer not registered. Cannot remove observer.");
	}
	/**
	 * Triggers an event for all observers
	 * @param id event identifier
	 * @param val
	 */
	public synchronized void updateObservers(String id,Object val){
		final String idVal = id;
		final Object v = val; 
		for (Observer o : observers){
			try{
				o.onObservation(idVal, v);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
